package cn.gdcp.materialdtest;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends AppCompatActivity  implements IOnDelListener{
       Button btnAdd;
       SQLiteDatabase database;
       EditText nameEdit;
       EditText ageEdit;
       EditText numberEdit;
       TextView readText;
       EditText findEdit;
       Button btnFind;
       TextView studentText;
      StuAdapter stuAdapter;
    ArrayList<Student> studentList;
    ListView listView;
     private ArrayList<Student> searchList=new ArrayList<>();
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initAtionBar();
        initButtonView();
        initStudentList();
        initAdapter();
        initListView();
        findEdit=findViewById(R.id.findE);
        }

    private void initListView() {
         listView=findViewById(R.id.listView);
         listView.setAdapter(stuAdapter);
    }

    private void initAdapter() {
        stuAdapter=new StuAdapter(MainActivity.this,studentList,MainActivity.this);
    }

    private void initButtonView() {
        btnAdd=findViewById(R.id.add_button);
        btnAdd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,AddStudent.class);
                startActivityForResult(intent,101);

            }
        });
        btnFind=findViewById(R.id.find_student_button);
        btnFind.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                findContent(v);
            }
        });
    }

    private void initAtionBar() {
        Toolbar toolbar=findViewById(R.id.toolbal);
        setSupportActionBar(toolbar);
        if (getSupportActionBar()!=null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            //  getSupportActionBar().setHomeAsUpIndicator(R.drawable.fh);
        }

    }

    public boolean  onOptionsItemSelected(MenuItem item){
      switch (item.getItemId()){
          case android.R.id.home:
               stuAdapter.changeData(studentList);
            //   stuAdapter.notifyDataSetChanged();
          break;
      }
        return true;
    }
    private void findContent(View view) {
        if (searchList!=null){
            searchList.clear();
        }
        String content=findEdit.getText().toString().trim();
        for (int i=0;i<studentList.size();i++){
            String studentName=studentList.get(i).getName();
            String studentAge=String.valueOf(studentList.get(i).getAge());
            String studentNum=String.valueOf(studentList.get(i).getId());
         if (studentName.contains(content)){
          //   Log.e("main",studentList.get(i).getName());
             searchList.add(studentList.get(i));
             stuAdapter.changeData(searchList);
             }
             else  if (studentAge.contains(content)){
             searchList.add(studentList.get(i));
             stuAdapter.changeData(searchList);
         }
            else  if (studentNum.contains(content)){
             searchList.add(studentList.get(i));
             stuAdapter.changeData(searchList);
         }
             else {

             Snackbar.make(view,"找不到该学生信息",Snackbar.LENGTH_SHORT).setAction("undo", new View.OnClickListener() {
                 @Override
                 public void onClick(View v) {

                 }
             }).show();


         }

        }
    }

    /**
     * 遍历数据库表中每行记录显示在listView的子项中
     */
    private void initStudentList() {
        studentList=new ArrayList<>();
        if (database==null){
            createOrOpenDataBase();
            Log.e("Main","11111");
        }
        String sql="create table  if not exists Student(" +
                "number int primary key," +
                "name text," +
                "age int )";
        database.execSQL(sql);
        int number;
        String name;
        int age;
        Cursor cursor=database.query("Student",null,null,null,null,null,null);
        for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            number=cursor.getInt(0);
            name=cursor.getString(1);
            age=cursor.getInt(2);
          Student student=new Student(number,name,age);
            Log.e("Main",name);
          studentList.add(student);
        }

        cursor.close();
    }



    private void findStudent(String content,View v) {
        if (database==null){
            createOrOpenDataBase();
        }
        int number;
        String name;
        int age;
        Cursor cursor=database.query("Student",null,null,null,null,null,null);
        for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            number=cursor.getInt(0);
            name=cursor.getString(1);
            age=cursor.getInt(2);
            if (String.valueOf(number).contains(content)){
                 studentText.setText(name+"  "+age);
            }else if (String.valueOf(age).contains(content)){
                studentText.setText(name+"  "+number);
            }else if (name.contains(content)){
                studentText.setText(""+number+"  "+age);
            }else {
            }

        }
        cursor.close();


    }








    private void createOrOpenDataBase() {
           String path=getFilesDir()+ File.separator+"stu.db";
            database=SQLiteDatabase.openOrCreateDatabase(path,null);
           LogUtil.e("MainActivity","create database sussce");
    }



    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==101&&resultCode==202){
            String name= data.getStringExtra("NAME");
            Log.e("main",name);
            int age=Integer.parseInt(data.getStringExtra("AGE"));
            int id=Integer.parseInt(data.getStringExtra("ID"));
             Student student=new Student(id,name,age);
               insertData(id,name,age);
         studentList.add(student);
        stuAdapter.notifyDataSetChanged();
        }

    }

    private void insertData(int id, String name, int age) {
        if(database==null){
            createOrOpenDataBase();
        }
       Log.e("main",name);
       String sql="insert into Student values('"+id+"','"+name+"','"+age+"')";
         database.execSQL(sql);
    }

    @Override
    public void del(int i) {
           deleteDate(i);
           studentList.remove(i);
           stuAdapter.notifyDataSetChanged();

    }

    private void deleteDate(int i) {
        if (database==null){
            createOrOpenDataBase();
        }
        String sql="delete from Student " +
                "where number='"+studentList.get(i).getId()+"'";
        database.execSQL(sql);
    }
}
